<template>
  <div class="dashboard-container">
    <div class="header-container">
      <h5 class="panel-title">报警管理</h5>
      <div class="alarm-stats">
        <div class="stat-item">
          <span class="stat-icon">❌</span>
          <span class="stat-label">紧急报警</span>
          <span class="stat-value">{{ alarmStats.critical }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-icon">⚠️</span>
          <span class="stat-label">严重警告</span>
          <span class="stat-value">{{ alarmStats.serious }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-icon">🔔</span>
          <span class="stat-label">一般提醒</span>
          <span class="stat-value">{{ alarmStats.general }}</span>
        </div>
      </div>
    </div>

    <el-card class="alarm-table-card">
      <el-table
        :data="alarmData"
        :key="tableUpdateKey"
        style="width: 100%"
        header-row-class-name="custom-header"
        class="alarm-table"
      >
        <el-table-column prop="level" label="报警级别">
          <template #default="{ row }">
            <div class="alarm-level">
              <div
                class="level-icon"
                :style="{ color: getLevelColor(row.rawData?.alarmLevel || 0) }"
              >
                {{ getLevelIcon(row.rawData?.alarmLevel || 0) }}
              </div>
              <span
                class="level-text"
                :style="{ color: getLevelColor(row.rawData?.alarmLevel || 0) }"
              >
                {{ getLevelText(row.rawData?.alarmLevel || 0) }}
              </span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="type" label="报警类型">
          <template #default="{ row }">
            <div class="alarm-type">
              <span
                class="type-text"
                :style="{ color: getLevelColor(row.rawData?.alarmLevel || 0) }"
              >
                {{ row.device }}
              </span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="device" label="设备名称" />
        <el-table-column prop="time" label="发生时间" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue';
  import { ElTable, ElTableColumn, ElCard } from 'element-plus';
  import { useWebsocketStoreWithOut } from '/@/store/modules/thingsboard/websocket';

  // 接口定义
  interface AlarmData {
    id: string;
    level: string;
    type: string;
    device: string;
    time: string;
    status: number;
    deviceId: string;
    rawData: {
      alarmLevel: number;
      alarmType: number;
      alarmStatus: number;
      temperature?: number;
      speedDeviation?: number;
    };
    lastUpdateTime?: number;
    updateKey?: number;
  }

  interface Device {
    id: string;
    name: string;
  }

  // 设备名称映射
  const deviceNameMapping: Record<string, string> = {
    ASRS_03: 'AS/RS-03',
    MTR_12: 'MTR-12',
    CONVEYOR_05: 'CONVEYOR-05',
  };

  // 报警类型映射
  const alarmTypeMapping: Record<number, string> = {
    0: '一般提醒',
    1: '堆垛机碰撞',
    2: '电机过温',
    3: '速度偏差',
  };

  // 设备数据
  const devices: Device[] = [
    { id: 'a666deb0-7bd7-11f0-b22d-51e2a3068019', name: 'ASRS_03' },
    { id: 'a66a8830-7bd7-11f0-b22d-51e2a3068019', name: 'MTR_12' },
    { id: 'a66e7fd0-7bd7-11f0-b22d-51e2a3068019', name: 'CONVEYOR_05' },
  ];

  // 响应式数据
  const alarmData = ref<AlarmData[]>([]);
  const tableUpdateKey = ref(0);

  // 定时器变量
  let pollingTimer: NodeJS.Timeout | null = null;
  let timeUpdateTimer: NodeJS.Timeout | null = null;

  // WebSocket相关
  const websocketReady = ref(false);
  const devicesInitialized = ref(false);
  const subscriptionMap = new Map<number, string>();
  
  // WebSocket实例
  let socket: WebSocket | null = null;

  // 初始化WebSocket连接，与MotorHealth.vue中使用相同的方式
  const initWebSocket = () => {
    const websocketStore = useWebsocketStoreWithOut();
    const wsUrl = websocketStore.getBackendWsUrl;
    
    try {
      socket = new WebSocket(wsUrl);
      
      socket.onopen = () => {
        websocketReady.value = true;
        console.log('✅ AlarmManagement WebSocket连接成功');
        if (devicesInitialized.value) {
          sendAlarmSubscriptionRequests();
        }
      };
      
      socket.onmessage = (event) => handleAlarmWebSocketMessage(event.data);
      
      socket.onerror = (error) => {
        console.error('WebSocket错误:', error);
      };
      
      socket.onclose = () => {
        console.log('WebSocket连接已关闭，尝试重新连接...');
        // 延迟重连
        setTimeout(() => {
          initWebSocket();
        }, 5000);
      };
    } catch (error) {
      console.error('创建WebSocket连接失败:', error);
    }
  };

  // 发送消息方法
  const send = (message: string) => {
    if (socket && socket.readyState === WebSocket.OPEN) {
      socket.send(message);
    }
  };

  // 打开连接方法
  const open = () => {
    if (!socket || socket.readyState !== WebSocket.OPEN) {
      initWebSocket();
    }
  };

  // 关闭连接方法
  const close = () => {
    if (socket) {
      socket.close();
    }
  };

  // 报警统计
  const alarmStats = computed(() => {
    const stats = { critical: 0, serious: 0, general: 0 };
    alarmData.value.forEach((alarm) => {
      const level = alarm.rawData?.alarmLevel || 0;
      if (level === 2) stats.critical++;
      else if (level === 1) stats.serious++;
      else stats.general++;
    });
    return stats;
  });

  // 获取报警级别颜色
  const getLevelColor = (level: number): string => {
    switch (level) {
      case 0:
        return '#00C851'; // 绿色
      case 1:
        return '#ff9800'; // 橙色
      case 2:
        return '#f44336'; // 红色
      default:
        return '#00C851';
    }
  };

  // 获取报警级别图标
  const getLevelIcon = (level: number): string => {
    switch (level) {
      case 0:
        return '🔔'; // 一般提醒
      case 1:
        return '⚠️'; // 严重警告
      case 2:
        return '❌'; // 紧急报警
      default:
        return '🔔';
    }
  };

  // 获取报警级别文本
  const getLevelText = (level: number): string => {
    switch (level) {
      case 0:
        return '一般提醒';
      case 1:
        return '严重警告';
      case 2:
        return '紧急报警';
      default:
        return '一般提醒';
    }
  };

  // 报警类型颜色现在统一使用报警级别颜色 (getLevelColor)

  // 获取报警类型文本
  const getTypeText = (type: number): string => {
    return alarmTypeMapping[type] || '未知类型';
  };

  // 初始化报警数据
  const initializeAlarmData = () => {
    alarmData.value = [
      {
        id: '1',
        level: '一般提醒',
        type: '堆垛机碰撞',
        device: '堆垛机碰撞', // 顯示報警類型作為設備名稱
        time: '08/26 09:43',
        status: 1,
        deviceId: 'a666deb0-7bd7-11f0-b22d-51e2a3068019',
        rawData: { alarmLevel: 0, alarmType: 1, alarmStatus: 1, position: 0 },
      },
      {
        id: '2',
        level: '一般提醒',
        type: '电机过温',
        device: '电机过温', // 顯示報警類型作為設備名稱
        time: '08/26 09:43',
        status: 1,
        deviceId: 'a66a8830-7bd7-11f0-b22d-51e2a3068019',
        rawData: { alarmLevel: 0, alarmType: 2, alarmStatus: 1, temperature: 25 },
      },
      {
        id: '3',
        level: '一般提醒',
        type: '速度偏差',
        device: '速度偏差', // 顯示報警類型作為設備名稱
        time: '08/26 09:43',
        status: 1,
        deviceId: 'a66e7fd0-7bd7-11f0-b22d-51e2a3068019',
        rawData: { alarmLevel: 0, alarmType: 3, alarmStatus: 1, speedDeviation: 0 },
      },
    ];

    console.log('📊 初始化报警数据:', alarmData.value);
  };

  // 订阅方法
  const sendAlarmSubscriptionRequests = () => {
    let cmdIdCounter = 1;
    const INTERVAL_MS = 100;
    const BATCH_SIZE = 5;
    const deviceQueue = [...devices];

    const sendBatch = () => {
      if (deviceQueue.length === 0) return;

      const batch = deviceQueue.splice(0, BATCH_SIZE);
      batch.forEach((device) => {
        const currentCmdId = cmdIdCounter;
        const subscribeRequest = {
          tsSubCmds: [
            {
              cmdId: currentCmdId,
              entityId: device.id,
              entityType: 'DEVICE',
              scope: 'LATEST_TELEMETRY',
            },
          ],
        };
        subscriptionMap.set(cmdIdCounter, device.id);
        cmdIdCounter++;
        send(JSON.stringify(subscribeRequest));
        console.log('📡 已发送报警设备订阅:', device.id, subscribeRequest);
      });

      if (deviceQueue.length > 0) {
        setTimeout(sendBatch, INTERVAL_MS);
      }
    };

    setTimeout(sendBatch, INTERVAL_MS);
  };

  // WebSocket消息处理
  const handleAlarmWebSocketMessage = (rawData: string) => {
    try {
      const parsedData = JSON.parse(rawData);
      const isValidMessage =
        parsedData.hasOwnProperty('subscriptionId') &&
        parsedData.hasOwnProperty('data') &&
        Object.keys(parsedData.data).length > 0;

      if (!isValidMessage) {
        return;
      }

      const deviceId = subscriptionMap.get(parsedData.subscriptionId);
      if (!deviceId) {
        return;
      }

      const device = devices.find((d) => d.id === deviceId);
      if (!device) {
        return;
      }

      console.log(`📊 设备 ${device.name} 收到遥测数据:`, parsedData.data);
      console.log(`🔍 数据字段分析:`, Object.keys(parsedData.data));

      // 檢查是否包含報警相關字段
      const alarmFields = ['alarmLevel', 'alarmType', 'alarmStatus', 'speedDeviation'];
      const hasAlarmFields = alarmFields.some((field) => parsedData.data.hasOwnProperty(field));
      const basicFields = ['mode', 'status', 'temperature'];
      const hasBasicFields = basicFields.some((field) => parsedData.data.hasOwnProperty(field));

      console.log(
        `🔍 數據類型檢查: 包含報警字段=${hasAlarmFields}, 包含基礎字段=${hasBasicFields}`,
      );

      Object.entries(parsedData.data).forEach(([key, values]) => {
        if (!Array.isArray(values) || values.length === 0) return;
        const [timestamp, value] = values[0];
        console.log(`📈 處理字段: ${key} = ${value} (時間戳: ${timestamp})`);
        updateAlarmFromTelemetry(device, key, value, timestamp);
      });
    } catch (error) {
      console.error('❌ 报警消息处理失败:', error);
    }
  };

  // 从遥测数据更新报警信息
  const updateAlarmFromTelemetry = (
    device: Device,
    key: string,
    value: any,
    _timestamp: number,
  ) => {
    console.log(`📈 设备 ${device.name} 数据更新: ${key}=${value}`);

    // 根据设备ID匹配报警数据
    const alarmIndex = alarmData.value.findIndex((alarm) => alarm.deviceId === device.id);

    if (alarmIndex > -1) {
      const alarm = alarmData.value[alarmIndex];
      const field = key.toLowerCase();
      const numValue = Number(value);

      // 根據設備類型處理對應的關鍵參數
      const deviceName = device.name;
      console.log(`🎯 處理設備 ${deviceName} 的數據: ${key}=${value}`);

      switch (deviceName) {
        case 'ASRS_03': // 堆垛機碰撞
          if (field === 'position') {
            const position = numValue;
            console.log(`📍 ASRS_03 位置數據: ${position}`);

            // 根據位置偏差設定報警級別
            if (Math.abs(position) > 50) {
              alarm.rawData.alarmLevel = 2; // 緊急報警 - 紅色
              console.log(`🔴 位置偏差過大 ${position} - 緊急報警`);
            } else if (Math.abs(position) > 20) {
              alarm.rawData.alarmLevel = 1; // 嚴重警告 - 黃色
              console.log(`🟡 位置偏差偏高 ${position} - 嚴重警告`);
            } else {
              alarm.rawData.alarmLevel = 0; // 一般提醒 - 綠色
              console.log(`🟢 位置正常 ${position} - 一般提醒`);
            }
            alarm.rawData.position = position;
          }
          break;

        case 'MTR_12': // 電機過溫
          if (field === 'temperature') {
            let actualTemp = numValue;
            // 處理大數值的溫度轉換
            if (numValue > 1000) {
              actualTemp = numValue / 100;
              console.log(`🔄 MTR_12 溫度轉換: ${numValue} -> ${actualTemp}℃`);
            }

            // 根據溫度設定報警級別
            if (actualTemp > 90) {
              alarm.rawData.alarmLevel = 2; // 緊急報警 - 紅色
              console.log(`🔴 電機溫度過高 ${actualTemp}℃ - 緊急報警`);
            } else if (actualTemp > 70) {
              alarm.rawData.alarmLevel = 1; // 嚴重警告 - 黃色
              console.log(`🟡 電機溫度偏高 ${actualTemp}℃ - 嚴重警告`);
            } else {
              alarm.rawData.alarmLevel = 0; // 一般提醒 - 綠色
              console.log(`🟢 電機溫度正常 ${actualTemp}℃ - 一般提醒`);
            }
            alarm.rawData.temperature = actualTemp;
          }
          break;

        case 'CONVEYOR_05': // 速度偏差
          if (field === 'speeddeviation') {
            const speedDev = numValue;
            console.log(`⚡ CONVEYOR_05 速度偏差: ${speedDev}`);

            // 根據速度偏差設定報警級別
            if (Math.abs(speedDev) > 30) {
              alarm.rawData.alarmLevel = 2; // 緊急報警 - 紅色
              console.log(`🔴 速度偏差過大 ${speedDev} - 緊急報警`);
            } else if (Math.abs(speedDev) > 15) {
              alarm.rawData.alarmLevel = 1; // 嚴重警告 - 黃色
              console.log(`🟡 速度偏差偏高 ${speedDev} - 嚴重警告`);
            } else {
              alarm.rawData.alarmLevel = 0; // 一般提醒 - 綠色
              console.log(`🟢 速度正常 ${speedDev} - 一般提醒`);
            }
            alarm.rawData.speedDeviation = speedDev;
          }
          break;

        default:
          console.log(`⚠️ 未知設備類型: ${deviceName}`);
      }

      alarm.time = new Date().toLocaleString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
      });

      console.log(`✅ 更新报警数据 ${alarm.device}:`, alarm);

      alarmData.value = [...alarmData.value];
      tableUpdateKey.value = Date.now();

      nextTick(() => {
        // 触发重新计算
      });
    }
  };

  // 启动时间更新定时器
  const startTimeUpdateTimer = () => {
    timeUpdateTimer = setInterval(() => {
      alarmData.value.forEach((alarm) => {
        if (alarm.status === 1) {
          // 活跃报警
          alarm.time = new Date().toLocaleString('zh-CN', {
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
          });
          alarm.lastUpdateTime = Date.now();
          alarm.updateKey = Date.now();
        }
      });

      alarmData.value = [...alarmData.value];
      console.log(`⏰ 时间更新: ${new Date().toLocaleTimeString()}`);
    }, 10000);
  };

  // 组件挂载
  const isMounted = ref(false);
  onMounted(async () => {
    if (isMounted.value) return;
    isMounted.value = true;

    console.log('🚀 报警管理组件启动');
    initializeAlarmData();

    devicesInitialized.value = true;
    startTimeUpdateTimer();

    setInterval(() => {
      tableUpdateKey.value = Date.now();
      console.log(`🔄 UI稳定刷新: ${new Date().toLocaleTimeString()}`);
    }, 8000);

    open();
  });

  onUnmounted(() => {
    close();

    if (pollingTimer) {
      clearInterval(pollingTimer);
    }

    if (timeUpdateTimer) {
      clearInterval(timeUpdateTimer);
    }

    console.log('🧹 报警管理组件资源已清理');
  });
</script>

<style scoped>
  .dashboard-container {
    background: rgba(255, 255, 255, 0.1);
    padding: 1vw;
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
  }

  .panel-title {
    margin: 0 0 1vw 0;
    font-size: 1vw;
    color: white;
  }

  .header-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1vw;
    flex-shrink: 0;
  }

  .alarm-stats {
    display: flex;
    gap: 1vw;
  }

  .stat-item {
    display: flex;
    align-items: center;
    gap: 0.3vw;
    color: white;
    font-size: 0.8vw;
  }

  .stat-icon {
    font-size: 1vw;
  }

  .stat-value {
    font-weight: bold;
    font-size: 1vw;
  }

  .alarm-table-card {
    background: transparent;
    border: none;
    box-shadow: none;
    flex: 1;
    min-height: 0;
  }

  :deep(.el-card__body) {
    padding: 0;
    height: 100%;
  }

  :deep(.alarm-table) {
    --el-table-border-color: rgba(255, 255, 255, 0.1);
    --el-table-text-color: rgba(255, 255, 255, 0.9);
    --el-table-header-text-color: rgba(255, 255, 255, 0.8);
    --el-table-row-hover-bg-color: rgba(255, 255, 255, 0.05);
    background: transparent;
    --el-table-tr-bg-color: transparent;
    font-size: 0.8vw;
  }

  :deep(.el-table th) {
    background: rgba(255, 255, 255, 0.08) !important;
  }

  :deep(.el-table td) {
    background: transparent !important;
    border-bottom: 0.2vh solid var(--el-table-border-color);
  }

  .alarm-level {
    display: flex;
    align-items: center;
    gap: 0.5vw;
  }

  .level-icon {
    font-size: 1vw;
  }

  .level-text {
    font-weight: 500;
  }

  .alarm-type {
    display: flex;
    align-items: center;
  }

  .type-text {
    font-weight: 500;
  }
</style>
